package com.jinlejia.bbs.logic;

import android.content.Context;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.bbs.bean.GambitBean;
import com.jinlejia.bbs.bean.GambitListBean;
import com.jinlejia.bbs.bean.base.BBSUserBean;
import com.jinlejia.bbs.bean.base.BannerBean;
import com.jinlejia.bbs.bean.base.InformationBean;
import com.jinlejia.bbs.bean.base.SoundBean;
import com.jinlejia.bbs.bean.base.TopicBean;
import com.jinlejia.bbs.http.entity.BannerEntity;
import com.jinlejia.bbs.http.entity.GambitEntity;
import com.jinlejia.bbs.http.entity.RecommendEntity;
import com.jinlejia.bbs.http.entity.UserEntity;
import com.jinlejia.bbs.http.entity.base.PageEntity;
import com.jinlejia.bbs.http.utils.BBSConfig;
import com.jinlejia.bbs.http.utils.HttpCallBack;
import com.jinlejia.bbs.http.utils.HttpUtils;

import java.util.ArrayList;
import java.util.List;

import static com.jinlejia.bbs.http.utils.HttpUtils.JsonParse;
import static com.jinlejia.bbs.http.utils.HttpUtils.httpCall;
import static com.jinlejia.bbs.http.utils.HttpUtils.httpCallBack;
import static com.jinlejia.bbs.http.utils.HttpUtils.httpCallForm;

/**
 * @author 王进 on 2019/3/22.
 */

public class GambitIndexLogic {
    private final Context context;
    private GambitListBean bean;
    private LogicCallBack callBack;
    private int maxCount = 0;
    private volatile int httpCount = 0;
    private int pageIndex;
    public GambitIndexLogic(Fragment fragment, GambitListBean bean, LogicCallBack callBack) {
        this.context = fragment.getContext();
        this.bean = bean;
        bean.setHotEnable(true); //启用热门话题
        this.callBack = callBack;
    }

    public void refresh(String keyWorld) {
        httpCount = 0;
        pageIndex = 1;
        loadBannerList(); //加载Banner列表
        loadRecommendList(); //加载话题列表
        listHomeTopic( pageIndex, keyWorld);
        maxCount = 3;
    }

    public void load(String keyWorld) {
        httpCount = 0;
        maxCount = 1;
        pageIndex = pageIndex + 1;
        listHomeTopic(pageIndex, keyWorld);
    }

    //获取Banner列表的接口
    private void loadBannerList() {
        httpCall(BBSConfig.adList).execute(httpCallBack(context, new HttpCallBack() {
            @Override
            public void onError(Exception e) {
                toCallBack(false);
            }

            @Override
            public void onResponse(JsonParse parse) {
                List<BannerEntity> data = parse.parseArray(BannerEntity.class);
                ArrayList<BannerBean> banners = new ArrayList<>();
                for (BannerEntity entity:data) {
                    BannerBean bean = new BannerBean();
                    bean.setImageUrl(BBSConfig.bannerUrl(entity.getImgUrl()));
                    bean.setLink(entity.getLink());
                    if (entity.getState()==1){
                        bean.setState(BannerBean.State.TOPIC);
                    }else {
                        bean.setState(BannerBean.State.WEB);
                    }
                    banners.add(bean);
                }

                bean.setBannerList(banners);
            }

            @Override
            public void onNoResponse(int code) {
                toCallBack(false);
            }
        }));

        toCallBack(false);
    }

    //获取推荐列表
    private void loadRecommendList() {
        HttpUtils.httpCall(BBSConfig.listRecommendUser)
                .execute(httpCallBack(context, new HttpCallBack() {
                            @Override
                            public void onError(Exception e) {
                                e.printStackTrace();
                                toCallBack(false);
                            }

                            @Override
                            public void onNoResponse(int code) {
                                toCallBack(false);
                            }

                            @Override
                            public void onResponse(JsonParse parse) {
                                List<RecommendEntity> list = parse.parseArray(RecommendEntity.class);
                                ArrayList<BBSUserBean> recommendList = new ArrayList<>();
                                if (list!=null)
                                for (RecommendEntity entity : list) {
                                    BBSUserBean bean = new BBSUserBean();
                                    bean.setUserPin(entity.getPin());
                                    bean.setUserName(entity.getUserName());
                                    bean.setUserAvatar(BBSConfig.headerUrl(entity.getUserImageUrl()));
                                    if (TextUtils.isEmpty(entity.getStoreName())){
                                        bean.setUserAddress(entity.getDeptName());
                                    }else {
                                        bean.setUserAddress(entity.getStoreName());
                                    }
                                    recommendList.add(bean);
                                }
                                bean.setRecommendList(recommendList);
                                toCallBack(false);
                            }
                        }
                ));
    }

    private void listHomeTopic(final int pageIndex, String keyWorld) {
        JSONObject json = new JSONObject();
        json.put("pageIndex", pageIndex);
        json.put("pageSize", 10);
        if (!TextUtils.isEmpty(keyWorld)) {
            json.put("keyWord", keyWorld);
        }
        httpCallForm(BBSConfig.listHomeTopic, json).execute(httpCallBack(context, new HttpCallBack() {
            @Override
            public void onError(Exception e) {
                toCallBack(false);
                e.printStackTrace();
            }

            @Override
            public void onNoResponse(int code) {
                if (code==204){
                    bean.getGambitBeans().clear();
                }
                toCallBack(false);
            }

            @Override
            public void onResponse(JsonParse parse) {
                TypeReference<PageEntity<GambitEntity>> reference = new TypeReference<PageEntity<GambitEntity>>() {
                };
                PageEntity<GambitEntity> response = parse.parsePageEntity(reference);
                List<GambitEntity> data = response.getData();
                ArrayList<GambitBean> list = new ArrayList<>();
                for (GambitEntity entity : data) {
                    GambitBean bean = new GambitBean();
                    //组装 话题
                    TopicBean topic = new TopicBean();
                    String topicTitle = entity.getTopicTitle();
                    topic.setTopicTitle(topicTitle);
                    topic.setReviewCount(entity.getReviewNum());
                    topic.setTopicCode(entity.getTopicCode());
                    bean.setTopic(topic);

                    InformationBean info = null;
                    if (!TextUtils.isEmpty(entity.getContent()) || !TextUtils.isEmpty(entity.getContent())){
                        info = new InformationBean();
                        if (entity.getContentType()==1){
                            info.setMessageContent(entity.getContent()); //回答内容
                        }else if (entity.getContentType()==2){
                            info.setSoundContent(SoundBean.create(entity.getContent())); //回答内容
                        }
                        info.setAnswerCode(entity.getAnswerCode());
                        info.setReviewCount(entity.getReviewNum()); //回答阅读次数
                        info.setLikeCount(entity.getSupportCount()); //回答点赞次数
                        info.setOwnLike(entity.getIsUser() == 1); //是否自己已经点赞

                        //region 组装回答用户
                        BBSUserBean user = new BBSUserBean();
                        user.setUserPin(entity.getUserPin()); //回答用户PIN
                        user.setUserName(entity.getUserName());//回答用户姓名
                        user.setUserAvatar(BBSConfig.headerUrl(entity.getUserImageUrl())); //回答用户头像
                        if (!TextUtils.isEmpty(entity.getAnswerStoreName())){
                            user.setUserAddress(entity.getAnswerStoreName()); //回答用户门店
                        }else {
                            user.setUserAddress(entity.getUserTitleLevel());
                        }
                        user.setUserDuty(entity.getUserTitleLevel()); //回答用户职务
                        info.setUser(user);
                        //endregion
                        List<UserEntity> recordsUserResults = entity.getAttitudesRecordsUserResults();
                        List<BBSUserBean> likeList = new ArrayList<>();
                        if (recordsUserResults!=null){
                            for (UserEntity userEntity:recordsUserResults) {
                                String imageUrl = userEntity.getImageUrl();
                                String pin = userEntity.getPin();
                                BBSUserBean likeUser = new BBSUserBean();
                                likeUser.setUserAvatar(BBSConfig.headerUrl(imageUrl));
                                likeUser.setUserPin(pin);
                                likeList.add(likeUser);
                            }
                        }
                        info.setOwnLike(entity.getIsUser()==1);
                        info.setLikeUserList(likeList);
                    }
                    bean.setInfo(info);

                    list.add(bean);
                }
                if (pageIndex==1){
                    bean.setGambitBeans(list);
                }else {
                    bean.getGambitBeans().addAll(list);
                }
                boolean pageAvailable = response.getNextPageAvailable();
                toCallBack(pageAvailable);
            }
        }));
    }
    //获取话题列表
    private boolean tempNextPage;
    private void toCallBack(boolean nextPage) {
        httpCount = httpCount + 1;
        if (httpCount == maxCount) {
            if (callBack != null) {
                callBack.onResult(nextPage);
            }
        }
    }

    public interface LogicCallBack {
        void onResult(boolean hasNextPage);

    }
}
